{% extends 'base.html' %}
{% load static %}

{% block title %}API配置编辑器 - Creeps Judge{% endblock %}

{% block extra_css %}
<style>
        .config-container {
            max-width: 1200px;
            margin: 20px auto;
            padding: 0;
            color: rgba(255, 255, 255, 0.9);
        }

        .config-header {
            background: linear-gradient(135deg, rgba(100, 150, 255, 0.1), rgba(0, 212, 255, 0.1));
            backdrop-filter: blur(10px);
            border: 1px solid rgba(100, 150, 255, 0.2);
            border-radius: 15px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2), 0 0 15px rgba(100, 150, 255, 0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .config-header h1 {
            color: #2c3e50;
            font-size: 1.8em;
            display: flex;
            align-items: center;
        }

        .config-header h1 i {
            margin-right: 15px;
            color: #667eea;
        }

        .header-actions {
            display: flex;
            gap: 15px;
        }

        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 0.9em;
            font-weight: 500;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-primary {
            background: linear-gradient(135deg, rgba(100, 150, 255, 0.8), rgba(0, 212, 255, 0.8));
            border: 2px solid rgba(255, 255, 255, 0.3);
            color: white;
            backdrop-filter: blur(5px);
            text-shadow: 0 0 8px rgba(255, 255, 255, 0.3);
            position: relative;
            overflow: hidden;
            transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
        }

        .btn-primary::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
            transition: left 0.5s ease;
        }

        .btn-primary:hover {
            background: linear-gradient(135deg, rgba(0, 212, 255, 1), rgba(100, 150, 255, 1));
            border-color: rgba(255, 255, 255, 0.6);
            box-shadow: 0 0 15px rgba(100, 150, 255, 0.4);
            transform: translateY(-3px);
        }

        .btn-primary:hover::before {
            left: 100%;
        }

        .btn-secondary {
            background: rgba(108, 117, 125, 0.8);
            border: 2px solid rgba(255, 255, 255, 0.3);
            color: white;
            backdrop-filter: blur(5px);
            text-shadow: 0 0 8px rgba(255, 255, 255, 0.3);
        }

        .btn-secondary:hover {
            background: rgba(90, 98, 104, 1);
            border-color: rgba(255, 255, 255, 0.6);
            box-shadow: 0 0 15px rgba(108, 117, 125, 0.4);
            transform: translateY(-2px);
        }

        .btn-success {
            background: linear-gradient(135deg, rgba(40, 167, 69, 0.8), rgba(32, 201, 151, 0.8));
            border: 2px solid rgba(255, 255, 255, 0.3);
            color: white;
            backdrop-filter: blur(5px);
            text-shadow: 0 0 8px rgba(255, 255, 255, 0.3);
        }

        .btn-success:hover {
            background: linear-gradient(135deg, rgba(40, 167, 69, 1), rgba(32, 201, 151, 1));
            border-color: rgba(255, 255, 255, 0.6);
            box-shadow: 0 0 15px rgba(40, 167, 69, 0.4);
            transform: translateY(-2px);
        }

        .editor-container {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
            min-height: 70vh;
        }

        .editor-panel {
            display: flex;
            flex-direction: column;
            background: linear-gradient(135deg, rgba(45, 55, 85, 0.3) 0%, rgba(35, 45, 75, 0.4) 100%);
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3), 0 0 20px rgba(100, 150, 255, 0.2);
            backdrop-filter: blur(15px);
            border: 2px solid rgba(100, 150, 255, 0.3);
            color: rgba(255, 255, 255, 0.9);
        }

        .panel-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 2px solid rgba(100, 150, 255, 0.3);
        }

        .panel-header h3 {
            color: rgba(255, 255, 255, 0.9);
            font-size: 1.2em;
            display: flex;
            align-items: center;
        }

        .panel-header h3 i {
            margin-right: 10px;
            color: #667eea;
        }

        .code-editor {
            flex: 1;
            border: 2px solid rgba(100, 150, 255, 0.3);
            border-radius: 8px;
            font-family: 'Courier New', monospace;
            font-size: 14px;
            padding: 15px;
            resize: none;
            outline: none;
            transition: all 0.3s ease;
            background: linear-gradient(135deg, rgba(45, 55, 85, 0.4) 0%, rgba(35, 45, 75, 0.5) 100%);
            color: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(10px);
        }

        .code-editor::placeholder {
            color: rgba(255, 255, 255, 0.5);
        }

        .code-editor:focus {
            border-color: rgba(100, 150, 255, 0.6);
            box-shadow: 0 0 20px rgba(100, 150, 255, 0.3);
            background: linear-gradient(135deg, rgba(0, 0, 0, 0.95) 0%, rgba(20, 20, 40, 1) 100%);
        }

        .preview-area {
            flex: 1;
            border: 2px solid #eee;
            border-radius: 8px;
            padding: 15px;
            background: #f8f9fa;
            overflow-y: auto;
        }

        .status-bar {
            background: rgba(255, 255, 255, 0.9);
            padding: 10px 20px;
            border-radius: 8px;
            margin-top: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 0.9em;
        }

        .status-indicator {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .status-indicator.success {
            color: #28a745;
        }

        .status-indicator.error {
            color: #dc3545;
        }

        .status-indicator.warning {
            color: #ffc107;
        }

        .api-preview-card {
            background: linear-gradient(135deg, rgba(0, 0, 0, 0.8) 0%, rgba(30, 30, 60, 0.9) 100%);
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 25px;
            border: 2px solid rgba(100, 150, 255, 0.3);
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2), 0 0 15px rgba(100, 150, 255, 0.1);
            backdrop-filter: blur(15px);
            color: rgba(255, 255, 255, 0.9);
        }

        .api-preview-card h4 {
            color: rgba(255, 255, 255, 0.95);
            margin-bottom: 15px;
            font-size: 1em;
            text-shadow: 0 0 10px rgba(255, 255, 255, 0.3);
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .api-preview-card .syntax {
            background: #2c3e50;
            color: white;
            padding: 8px 12px;
            border-radius: 4px;
            font-family: 'Courier New', monospace;
            font-size: 0.85em;
            margin: 8px 0;
        }

        .api-preview-card .description {
            color: #666;
            font-size: 0.9em;
            line-height: 1.4;
        }

        .error-message {
            background: linear-gradient(135deg, rgba(220, 53, 69, 0.2) 0%, rgba(200, 35, 51, 0.2) 100%);
            color: rgba(255, 100, 120, 0.9);
            padding: 15px 20px;
            border-radius: 12px;
            margin-bottom: 20px;
            border: 2px solid rgba(220, 53, 69, 0.4);
            backdrop-filter: blur(10px);
            box-shadow: 0 4px 15px rgba(220, 53, 69, 0.2);
            font-weight: 500;
        }

        .success-message {
            background: linear-gradient(135deg, rgba(40, 167, 69, 0.2) 0%, rgba(32, 201, 151, 0.2) 100%);
            color: rgba(80, 200, 120, 0.9);
            padding: 15px 20px;
            border-radius: 12px;
            margin-bottom: 20px;
            border: 2px solid rgba(40, 167, 69, 0.4);
            backdrop-filter: blur(10px);
            box-shadow: 0 4px 15px rgba(40, 167, 69, 0.2);
            font-weight: 500;
        }

        .toolbar {
            display: flex;
            gap: 10px;
            margin-bottom: 15px;
            padding: 15px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 10px;
            border: 1px solid rgba(100, 150, 255, 0.3);
            backdrop-filter: blur(10px);
        }

        .toolbar .btn {
            padding: 8px 15px;
            font-size: 0.85em;
        }

        @media (max-width: 1200px) {
            .editor-container {
                grid-template-columns: 1fr;
                gap: 20px;
            }
        }

        @media (max-width: 768px) {
            .config-container {
                padding: 10px;
            }

            .config-header {
                flex-direction: column;
                gap: 15px;
                text-align: center;
            }

            .header-actions {
                flex-wrap: wrap;
                justify-content: center;
            }
        }
</style>
{% endblock %}

{% block content %}
    <div class="config-container">
        <div class="config-header">
            <h1><i class="fas fa-cogs"></i> API配置编辑器</h1>
            <div class="header-actions">
                <a href="/api-docs/" class="btn btn-secondary">
                    <i class="fas fa-eye"></i> 预览文档
                </a>
                <button class="btn btn-primary" onclick="saveConfig()">
                    <i class="fas fa-save"></i> 保存配置
                </button>
            </div>
        </div>

        <div class="editor-container">
            <!-- 编辑器面板 -->
            <div class="editor-panel">
                <div class="panel-header">
                    <h3><i class="fas fa-code"></i> JSON 配置编辑器</h3>
                    <div class="toolbar">
                        <button class="btn btn-secondary" onclick="formatJSON()">
                            <i class="fas fa-indent"></i> 格式化
                        </button>
                        <button class="btn btn-secondary" onclick="validateJSON()">
                            <i class="fas fa-check-circle"></i> 验证
                        </button>
                        <button class="btn btn-secondary" onclick="resetConfig()">
                            <i class="fas fa-undo"></i> 重置
                        </button>
                    </div>
                </div>
                <textarea id="configEditor" class="code-editor" placeholder="在此编辑API配置JSON...">{{ config_json }}</textarea>
                <div class="status-bar">
                    <div id="statusIndicator" class="status-indicator">
                        <i class="fas fa-circle"></i>
                        <span>就绪</span>
                    </div>
                    <div>
                        <span id="lineCount">行数: 0</span> | 
                        <span id="charCount">字符: 0</span>
                    </div>
                </div>
            </div>

            <!-- 预览面板 -->
            <div class="editor-panel">
                <div class="panel-header">
                    <h3><i class="fas fa-eye"></i> 实时预览</h3>
                    <button class="btn btn-secondary" onclick="refreshPreview()">
                        <i class="fas fa-sync-alt"></i> 刷新预览
                    </button>
                </div>
                <div id="previewArea" class="preview-area">
                    <p style="color: #666; text-align: center; margin-top: 50px;">
                        <i class="fas fa-spinner fa-spin"></i> 加载预览中...
                    </p>
                </div>
            </div>
        </div>
    </div>

    <script>
        let originalConfig = {{ config_json|safe }};
        let currentConfig = null;

        // 初始化编辑器
        document.addEventListener('DOMContentLoaded', function() {
            const editor = document.getElementById('configEditor');
            
            // 监听编辑器变化
            editor.addEventListener('input', function() {
                updateStats();
                validateJSON();
                debouncePreview();
            });

            // 初始化统计和预览
            updateStats();
            refreshPreview();
        });

        // 更新统计信息
        function updateStats() {
            const editor = document.getElementById('configEditor');
            const content = editor.value;
            const lines = content.split('\n').length;
            const chars = content.length;
            
            document.getElementById('lineCount').textContent = `行数: ${lines}`;
            document.getElementById('charCount').textContent = `字符: ${chars}`;
        }

        // 验证JSON格式
        function validateJSON() {
            const editor = document.getElementById('configEditor');
            const statusIndicator = document.getElementById('statusIndicator');
            
            try {
                currentConfig = JSON.parse(editor.value);
                statusIndicator.className = 'status-indicator success';
                statusIndicator.innerHTML = '<i class="fas fa-check-circle"></i><span>JSON格式正确</span>';
                return true;
            } catch (error) {
                statusIndicator.className = 'status-indicator error';
                statusIndicator.innerHTML = `<i class="fas fa-exclamation-circle"></i><span>JSON格式错误: ${error.message}</span>`;
                return false;
            }
        }

        // 格式化JSON
        function formatJSON() {
            const editor = document.getElementById('configEditor');
            try {
                const parsed = JSON.parse(editor.value);
                editor.value = JSON.stringify(parsed, null, 2);
                updateStats();
                validateJSON();
                refreshPreview();
            } catch (error) {
                alert('JSON格式错误，无法格式化: ' + error.message);
            }
        }

        // 重置配置
        function resetConfig() {
            if (confirm('确定要重置到原始配置吗？这将丢失所有未保存的更改。')) {
                document.getElementById('configEditor').value = JSON.stringify(originalConfig, null, 2);
                updateStats();
                validateJSON();
                refreshPreview();
            }
        }

        // 防抖预览更新
        let previewTimeout;
        function debouncePreview() {
            clearTimeout(previewTimeout);
            previewTimeout = setTimeout(refreshPreview, 1000);
        }

        // 刷新预览
        function refreshPreview() {
            const previewArea = document.getElementById('previewArea');
            
            if (!validateJSON()) {
                previewArea.innerHTML = '<div class="error-message"><i class="fas fa-exclamation-triangle"></i> JSON格式错误，无法生成预览</div>';
                return;
            }

            try {
                const config = currentConfig;
                let html = '';

                // 显示API信息
                if (config.api_info) {
                    html += `
                        <div class="api-preview-card">
                            <h4><i class="fas fa-info-circle"></i> ${config.api_info.title || 'API文档'}</h4>
                            <div class="description">${config.api_info.description || ''}</div>
                            <small style="color: #666;">版本: ${config.api_info.version || '1.0.0'}</small>
                        </div>
                    `;
                }

                // 显示分类和API
                if (config.categories && config.categories.length > 0) {
                    config.categories.forEach(category => {
                        html += `
                            <div class="api-preview-card">
                                <h4><i class="fas fa-folder"></i> ${category.name || '未命名分类'}</h4>
                                <div class="description">${category.description || ''}</div>
                                <small style="color: #666;">包含 ${(category.apis || []).length} 个API</small>
                            </div>
                        `;

                        if (category.apis && category.apis.length > 0) {
                            category.apis.slice(0, 3).forEach(api => {
                                html += `
                                    <div class="api-preview-card" style="margin-left: 20px; border-left-color: #28a745;">
                                        <h4><i class="fas fa-function"></i> ${api.name || '未命名API'}</h4>
                                        <div class="syntax">${api.syntax || ''}</div>
                                        <div class="description">${api.description || ''}</div>
                                    </div>
                                `;
                            });
                            
                            if (category.apis.length > 3) {
                                html += `<div style="margin-left: 20px; color: #666; font-style: italic;">... 还有 ${category.apis.length - 3} 个API</div>`;
                            }
                        }
                    });
                } else {
                    html += '<div class="error-message"><i class="fas fa-exclamation-triangle"></i> 没有找到API分类</div>';
                }

                // 显示数据类型
                if (config.data_types && Object.keys(config.data_types).length > 0) {
                    html += `
                        <div class="api-preview-card">
                            <h4><i class="fas fa-database"></i> 数据类型</h4>
                            <div class="description">定义了 ${Object.keys(config.data_types).length} 个数据类型</div>
                        </div>
                    `;
                }

                // 显示示例
                if (config.examples && config.examples.length > 0) {
                    html += `
                        <div class="api-preview-card">
                            <h4><i class="fas fa-lightbulb"></i> 示例代码</h4>
                            <div class="description">包含 ${config.examples.length} 个示例</div>
                        </div>
                    `;
                }

                previewArea.innerHTML = html || '<div style="color: #666; text-align: center; margin-top: 50px;">暂无内容</div>';
            } catch (error) {
                previewArea.innerHTML = `<div class="error-message"><i class="fas fa-exclamation-triangle"></i> 预览生成失败: ${error.message}</div>`;
            }
        }

        // 保存配置
        function saveConfig() {
            if (!validateJSON()) {
                alert('JSON格式错误，无法保存');
                return;
            }

            const statusIndicator = document.getElementById('statusIndicator');
            statusIndicator.className = 'status-indicator warning';
            statusIndicator.innerHTML = '<i class="fas fa-spinner fa-spin"></i><span>保存中...</span>';

            fetch('/api-docs/save-config/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: document.getElementById('configEditor').value
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    statusIndicator.className = 'status-indicator success';
                    statusIndicator.innerHTML = '<i class="fas fa-check-circle"></i><span>保存成功</span>';
                    originalConfig = currentConfig;
                    
                    // 显示成功消息
                    const previewArea = document.getElementById('previewArea');
                    previewArea.insertAdjacentHTML('afterbegin', 
                        '<div class="success-message"><i class="fas fa-check-circle"></i> 配置已成功保存！</div>'
                    );
                    
                    setTimeout(() => {
                        const successMsg = previewArea.querySelector('.success-message');
                        if (successMsg) successMsg.remove();
                    }, 3000);
                } else {
                    throw new Error(data.error || '保存失败');
                }
            })
            .catch(error => {
                statusIndicator.className = 'status-indicator error';
                statusIndicator.innerHTML = `<i class="fas fa-exclamation-circle"></i><span>保存失败: ${error.message}</span>`;
                alert('保存失败: ' + error.message);
            });
        }

        // 键盘快捷键
        document.addEventListener('keydown', function(e) {
            if (e.ctrlKey || e.metaKey) {
                switch(e.key) {
                    case 's':
                        e.preventDefault();
                        saveConfig();
                        break;
                    case 'f':
                        e.preventDefault();
                        formatJSON();
                        break;
                }
            }
        });
    </script>
{% endblock %}